package com.gec.anan.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gec.anan.common.execption.AnanException;
import com.gec.anan.common.result.ResultCodeEnum;
import com.gec.anan.map.service.MapService;
import com.gec.anan.model.form.map.CalculateDrivingLineForm;
import com.gec.anan.model.vo.map.DrivingLineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Autowired
    RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key;
    /**
     * 获取驾驶路线
     * @param form
     * @return
     */
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm form) {
        //设置url
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";
        //封装map参数
        HashMap<String, String> map = new HashMap<>();
        map.put("from",form.getStartPointLatitude()+","+form.getStartPointLongitude());
        map.put("to", form.getEndPointLatitude()+","+form.getEndPointLongitude());
        log.info("key格式{}", key);
        map.put("key",key);
        //调用restemplate接口
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);
        //判断
        int status = result.getIntValue("status");
        if(status !=0){
            log.error("路线计算失败{}",result);
            throw new AnanException(ResultCodeEnum.MAP_FAIL );
        }
        //获取路线
        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        //封装线路信息
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        //封装距离
        drivingLineVo.setDistance(route.getBigDecimal("distance")
                .divide(new BigDecimal(1000))
                .setScale(2, RoundingMode.HALF_UP));
        //封装时间
        drivingLineVo.setDuration(route.getBigDecimal("duration"));
        //封装路线
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));
        return drivingLineVo;

    }
}
